package com.xzc.shopping.controller;

import com.xzc.shopping.common.BaseResponse;
import com.xzc.shopping.common.ErrorCode;
import com.xzc.shopping.common.ResultUtils;
import com.xzc.shopping.model.domain.User;
import com.xzc.shopping.model.dto.CartAddDTO;
import com.xzc.shopping.model.vo.CartListVO;
import com.xzc.shopping.model.vo.CartVO;
import com.xzc.shopping.service.CartService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import java.util.List;
import java.util.Map;

import static com.xzc.shopping.constant.UserConstant.USER_LOGIN_STATE;

@RestController
@RequestMapping("/cart")
public class CartController {

    @Resource
    private CartService cartService;

    /**
     * 添加购物车项
     */
    private final static Integer FORBID_VALUE = 0;
    private final static Integer NORMAL_VALUE = 0;

    @PostMapping("/add")
    public BaseResponse<Boolean> addCartItem(@RequestBody @Valid CartAddDTO dto,
                                             HttpServletRequest request) {
        // 参数校验
        if (dto.getProductId() == null ) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "参数不合法");
        }

        if(dto.getQuantity()<FORBID_VALUE) {
            dto.setQuantity(NORMAL_VALUE);
        }
        // 登录检查
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (user == null) {
            return ResultUtils.error(ErrorCode.NOT_LOGIN);
        }


        return cartService.addCartItem(user.getId(), dto);
    }

    /**
     * 获取购物车列表
     */
    @GetMapping("/list")
    public BaseResponse<List<CartVO>> getCartList(HttpServletRequest request) {
        // 登录检查
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (user == null) {
            return ResultUtils.error(ErrorCode.NOT_LOGIN);
        }

        return cartService.getCartList(user.getId());
    }

    /**
     * 删除购物车项（优化返回最新数据）
     */
    @DeleteMapping("/{cartId}")
    public BaseResponse<Boolean> deleteCartItem(@PathVariable Long cartId,
                                                   HttpServletRequest request) {
        User user = getLoginUser(request);
        if (user == null) {
            return ResultUtils.error(ErrorCode.NOT_LOGIN);
        }
        return cartService.deleteCartItem(user.getId(), cartId);
    }


    /**
     * 更新购物车数量（优化参数接收和返回）
     */
    @PutMapping("/{cartId}")
    public BaseResponse<CartListVO> updateQuantity(
            @PathVariable Long cartId,
            @RequestParam Integer quantity,
            HttpServletRequest request) {
        User user = getLoginUser(request);
        if (user == null) {
            return ResultUtils.error(ErrorCode.NOT_LOGIN);
        }
        if (quantity == null || quantity < 1) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "数量无效");
        }
        return cartService.updateQuantity(user.getId(), cartId, quantity);
    }

    private User getLoginUser(HttpServletRequest request) {
        return (User) request.getSession().getAttribute(USER_LOGIN_STATE);
    }

}
